import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/login.vue'
import Layout from '../views/layout/layout.vue'
import Articles from '../views/articles/articles.vue'
import Images from '../views/images/images.vue'
import Home from '../views/home/home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  // 用户登录通过之后访问的页面
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'articles',
        component: Articles
      },
      {
        path: 'images',
        component: Images
      },
      {
        path: 'home',
        component: Home
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
const pageList = ['/', '/images', '/articles', '/home']
// 守卫⚔执行!
router.beforeEach((to, from, next) => {
  console.log('路由发生变化喽^-^~', from, to)
  const token = localStorage.getItem('tokenStr')
  if (pageList.includes(to.path)) {
    if (token) {
      next()
    } else {
      console.log('你在干什么?')
      next('/login')
    }
    // 不能去login了差不多得了
  } else if (to.path === '/login') {
    if (token) {
      next('/')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
